package com.ship.dispatch.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ship.common.business.service.impl.BaseServiceImpl;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.dispatch.bean.SmShipFreightCost;
import com.ship.dispatch.bean.SpShipFreightAttachments;
import com.ship.dispatch.bean.boats.CreateFreightAttachmentsRq;
import com.ship.dispatch.bean.boats.CreateFreightRq;
import com.ship.dispatch.bean.fob.SpFobFileRecord;
import com.ship.dispatch.service.SmShipFreightCostService;
import com.ship.dispatch.mapper.SmShipFreightCostMapper;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.dispatch.service.SpShipFreightAttachmentsService;
import com.ship.dispatch.service.fob.SpFobJsfhccbItemsService;
import com.ship.dispatch.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
* @author zhangyh
* @description 针对表【sm_ship_freight_cost(船舶运费信息表)】的数据库操作Service实现
* @createDate 2024-01-29 15:52:05
*/
@Service
public class SmShipFreightCostServiceImpl extends BaseServiceImpl<SmShipFreightCostMapper, SmShipFreightCost>
    implements SmShipFreightCostService{

    @Autowired
    private SpShipFreightAttachmentsService spShipFreightAttachmentsService;

    @Autowired
    SpFobJsfhccbItemsService spFobJsfhccbItemsService;



    @Override
    public Long saveFreightCost(SmShipFreightCost cost) {
        if(StringUtils.isNotBlank(cost.getCharterCost())){
            cost.setCharterCost(new BigDecimal(cost.getCharterCost()).setScale(4, RoundingMode.HALF_UP).toString());
        }
        if(StringUtils.isNotBlank(cost.getShippingAgencyCost())){
            cost.setShippingAgencyCost(new BigDecimal(cost.getShippingAgencyCost()).setScale(4, RoundingMode.HALF_UP).toString());
        }
        if(StringUtils.isNotBlank(cost.getTotalTransportationCost())){
            cost.setTotalTransportationCost(new BigDecimal(cost.getTotalTransportationCost()).setScale(4, RoundingMode.HALF_UP).toString());
        }
        if(StringUtils.isNotBlank(cost.getShippingCost())){
            cost.setShippingCost(new BigDecimal(cost.getShippingCost()).setScale(4, RoundingMode.HALF_UP).toString());
        }

        cost.setCreateBy(SecurityUtils.getUsername());
        cost.setCreateDate(new Date());
        this.baseMapper.insert(cost);
        return cost.getId();
    }

    @Override
    public boolean addFreight(SpFobFileRecord record,CreateFreightRq rq) {
        SmShipFreightCost smShipFreightCost = new SmShipFreightCost();
        smShipFreightCost.setVoyageNumber(rq.getVoyageNumber());
        smShipFreightCost.setVesselName(rq.getShipName());
        smShipFreightCost.setImo(rq.getImo());
        smShipFreightCost.setDataSource("2");
        smShipFreightCost.setCreateBy(SecurityUtils.getUsername());
        smShipFreightCost.setCreateDate(new Date());
        boolean save = this.save(smShipFreightCost);
        String id = smShipFreightCost.getId().toString();
        if (null != record) {
            this.addFreightAttachments(record, id);
        }
        return save;
    }

    @Override
    public JsonResult addFreightAttachments(SpFobFileRecord fobFileRecord, String id) {
        try {
            URI httpUrl = null;
            InputStream inputStream = null;
            try {
                String encodedFilePath = fobFileRecord.getHttpPath().replace(" ", "%20");
                httpUrl = new URI(encodedFilePath);
                URL uri = httpUrl.toURL();
                inputStream = uri.openConnection().getInputStream();
            } catch (MalformedURLException e) {
                throw new RuntimeException(e);
            }
            List<SpShipFreightAttachments> freightAttachmentsList = new LinkedList<>();
            ExcelReader reader = ExcelUtil.getReader(inputStream);

            // 读取整个Sheet的数据
            List<List<Object>> read = reader.read();
            AtomicInteger i= new AtomicInteger();
            AtomicReference<String> tableName = new AtomicReference<>("CharterCost");
            List<Integer> list = new ArrayList<>();
            List<Integer> list1 = new ArrayList<>();
            read.forEach(column -> {
                if (i.getAndIncrement() < 2){
                    return;
                }
                String name = String.valueOf(column.get(0));
                String str = String.valueOf(column.get(0)).replaceAll("\\u00A0","");
                if (str.equals("Shippingagencycost")) {
                    tableName.set("ShippingAgencyCost");
                    return;
                }else if (str.equals("Insurance")) {
                    tableName.set("Insurance");
                    return;
                }else if (str.equals("LSMGO")) {
                    tableName.set("LSMGO");
                    return;
                }else if (str.equals("VLSFO")) {
                    tableName.set("VLSFO");
                    return;
                }else if (str.equals("Positioningfee")) {
                    tableName.set("PositioningFee");
                    list.add(i.getAndIncrement());
                    if (list.size() <= 1) {
                        return;
                    }
                }else if (str.equals("BallastBonus")) {
                    tableName.set("BallastBonus");
                    list1.add(i.getAndIncrement());
                    if (list1.size() <= 1) {
                        return;
                    }
                }else if (str.equals("BOG")) {
                    tableName.set("BOG");
                    return;
                }
                int index = i.getAndIncrement();
                SpShipFreightAttachments spShipFreightAttachments = new SpShipFreightAttachments();
                spShipFreightAttachments.setFreightId(Long.valueOf(id));
                if (!String.valueOf(column.get(0)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(0)))) {
                    spShipFreightAttachments.setTitle(String.valueOf(column.get(0)));
                }
                if (!String.valueOf(column.get(1)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(1)))) {
                    spShipFreightAttachments.setTableCell2(String.valueOf(column.get(1)));
                }
                if (!String.valueOf(column.get(2)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(2)))) {
                    spShipFreightAttachments.setTableCell3(String.valueOf(column.get(2)));
                }
                if (!String.valueOf(column.get(3)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(3)))) {
                    spShipFreightAttachments.setTableCell4(String.valueOf(column.get(3)));
                }
                if (!String.valueOf(column.get(4)).equals("null") && StringUtils.isNotBlank(String.valueOf(column.get(4)))) {
                    spShipFreightAttachments.setTableCell5(String.valueOf(column.get(4)));
                }
                spShipFreightAttachments.setSort(index+"");
                spShipFreightAttachments.setTableName(String.valueOf(tableName));
                spShipFreightAttachments.setCreateTime(new Date());
                spShipFreightAttachments.setUpdateTime(new Date());
                spShipFreightAttachments.setEnable("1");
                spShipFreightAttachments.setCreateUser(SecurityUtils.getUsername());
                spShipFreightAttachments.setUpdateUser(SecurityUtils.getUsername());
                freightAttachmentsList.add(spShipFreightAttachments);
            });
            if (CollectionUtil.isNotEmpty(freightAttachmentsList)){
                boolean b = spShipFreightAttachmentsService.saveBatch(freightAttachmentsList);
                this.updateFreightCostById(freightAttachmentsList,id);
                return JsonResult.success(b);

            }
        }catch (Exception e){
            return JsonResult.failed("上传失败，原因：" + e.getMessage());
        }
        return JsonResult.success();
    }

    private void updateFreightById(SpShipFreightAttachments freightAttachmentsList) {
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id",freightAttachmentsList.getFreightId());
        if (freightAttachmentsList.getTableName().equals("CharterCost")){
            if (freightAttachmentsList.getTitle().replaceAll("\\u00A0","").equals("Voyagestartdate")){
                updateWrapper.set("voyage_start_time",freightAttachmentsList.getTableCell2());
                baseMapper.update(null,updateWrapper);
            }
            if (freightAttachmentsList.getTitle().replaceAll("\\u00A0","").equals("Voyageenddate")){
                updateWrapper.set("voyage_end_time",freightAttachmentsList.getTableCell2());
                baseMapper.update(null,updateWrapper);
            }
            if ("Total".equals(freightAttachmentsList.getTitle())){
                updateWrapper.set("charter_cost",freightAttachmentsList.getTableCell2());
                baseMapper.update(null,updateWrapper);
            }
        }else if ("ShippingAgencyCost".equals(freightAttachmentsList.getTableName())){
//                    if ("装载港".equals(item.getTitle())){
//                        updateWrapper.set("loading_port",item.getTableCell2());
//                    }
//                    if ("卸载港".equals(item.getTitle())){
//                        updateWrapper.set("discharge_port",item.getTableCell2());
//                    }
            if ("Total".equals(freightAttachmentsList.getTitle())){
                updateWrapper.set("shipping_agency_cost",freightAttachmentsList.getTableCell2());
                baseMapper.update(null,updateWrapper);
            }
        }else if ("Insurance".equals(freightAttachmentsList.getTableName())){
            if ("Total".equals(freightAttachmentsList.getTitle())){
                updateWrapper.set("insurance",freightAttachmentsList.getTableCell2());
                baseMapper.update(null,updateWrapper);
            }
        }else if ("LSMGO".equals(freightAttachmentsList.getTableName())){
            if ("Total".equals(freightAttachmentsList.getTitle())){
                updateWrapper.set("lsmgo",freightAttachmentsList.getTableCell2());
                baseMapper.update(null,updateWrapper);
            }
        }else if ("VLSFO".equals(freightAttachmentsList.getTableName())){
            if ("Total".equals(freightAttachmentsList.getTitle())){
                updateWrapper.set("vlsfo",freightAttachmentsList.getTableCell2());
                baseMapper.update(null,updateWrapper);
            }
        }else if ("PositioningFee".equals(freightAttachmentsList.getTableName())){
            if ("Total".equals(freightAttachmentsList.getTitle())){
                updateWrapper.set("positioning_fee",freightAttachmentsList.getTableCell2());
                baseMapper.update(null,updateWrapper);
            }
        }else if ("BallastBonus".equals(freightAttachmentsList.getTableName())){
            if ("Total".equals(freightAttachmentsList.getTitle())){
                updateWrapper.set("ballast_bonus",freightAttachmentsList.getTableCell2());
                baseMapper.update(null,updateWrapper);
            }
        }else if ("BOG".equals(freightAttachmentsList.getTableName())){
            if ("Totalprice".equals(freightAttachmentsList.getTitle().replaceAll("\\u00A0",""))){
                updateWrapper.set("bog",freightAttachmentsList.getTableCell2());
                baseMapper.update(null,updateWrapper);
            }
            if ("TotalTransportationcost".equals(freightAttachmentsList.getTitle().replaceAll("\\u00A0",""))){
                updateWrapper.set("total_transportation_cost",freightAttachmentsList.getTableCell2());
                baseMapper.update(null,updateWrapper);
            }
            if ("Estimateddischargequantity".equals(freightAttachmentsList.getTitle().replaceAll("\\u00A0",""))){
                updateWrapper.set("estimated_discharge_quantity",freightAttachmentsList.getTableCell2());
                baseMapper.update(null,updateWrapper);
            }
            if ("Shippingcost".equals(freightAttachmentsList.getTitle().replaceAll("\\u00A0",""))){
                updateWrapper.set("shipping_cost",freightAttachmentsList.getTableCell2());
                baseMapper.update(null,updateWrapper);
            }
        }
    }

    private void updateFreightCostById(List<SpShipFreightAttachments> freightAttachmentsList, String id) {
        if (CollectionUtil.isNotEmpty(freightAttachmentsList)){
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.eq("id",id);
            freightAttachmentsList.forEach(item -> {
                if (item.getTableName().equals("CharterCost")){
                    if (item.getTitle().replaceAll("\\u00A0","").equals("Voyagestartdate")){
                        updateWrapper.set("voyage_start_time",item.getTableCell2());
                    }
                    if (item.getTitle().replaceAll("\\u00A0","").equals("Voyageenddate")){
                        updateWrapper.set("voyage_end_time",item.getTableCell2());
                    }
                    if ("Total".equals(item.getTitle())){
                        updateWrapper.set("charter_cost",item.getTableCell2());
                    }
                }else if ("ShippingAgencyCost".equals(item.getTableName())){
//                    if ("装载港".equals(item.getTitle())){
//                        updateWrapper.set("loading_port",item.getTableCell2());
//                    }
//                    if ("卸载港".equals(item.getTitle())){
//                        updateWrapper.set("discharge_port",item.getTableCell2());
//                    }
                    if ("Total".equals(item.getTitle())){
                        updateWrapper.set("shipping_agency_cost",item.getTableCell2());
                    }
                }else if ("Insurance".equals(item.getTableName())){
                    if ("Total".equals(item.getTitle())){
                        updateWrapper.set("insurance",item.getTableCell2());
                    }
                }else if ("LSMGO".equals(item.getTableName())){
                    if ("Total".equals(item.getTitle())){
                        updateWrapper.set("lsmgo",item.getTableCell2());
                    }
                }else if ("VLSFO".equals(item.getTableName())){
                    if ("Total".equals(item.getTitle())){
                        updateWrapper.set("vlsfo",item.getTableCell2());
                    }
                }else if ("PositioningFee".equals(item.getTableName())){
                    if ("Total".equals(item.getTitle())){
                        updateWrapper.set("positioning_fee",item.getTableCell2());
                    }
                }else if ("BallastBonus".equals(item.getTableName())){
                    if ("Total".equals(item.getTitle())){
                        updateWrapper.set("ballast_bonus",item.getTableCell2());
                    }
                }else if ("BOG".equals(item.getTableName())){
                    if ("Totalprice".equals(item.getTitle().replaceAll("\\u00A0",""))){
                        updateWrapper.set("bog",item.getTableCell2());
                    }
                    if ("TotalTransportationcost".equals(item.getTitle().replaceAll("\\u00A0",""))){
                        updateWrapper.set("total_transportation_cost",item.getTableCell2());
                    }
                    if ("Estimateddischargequantity".equals(item.getTitle().replaceAll("\\u00A0",""))){
                        updateWrapper.set("estimated_discharge_quantity",item.getTableCell2());
                    }
                    if ("Shippingcost".equals(item.getTitle().replaceAll("\\u00A0",""))){
                        updateWrapper.set("shipping_cost",item.getTableCell2());
                    }
                }
            });
            baseMapper.update(null,updateWrapper);
        }
    }

    @Override
    public boolean deleteFreight(List<String> ids) {
        //根据ID删除船舶运费信息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("id",ids);
        int delete = baseMapper.delete(queryWrapper);
        spShipFreightAttachmentsService.deleteFreightAttachments(ids);
        if (delete != 0){
            return true;
        }
        return false;
    }

    @Override
    public boolean updateFreightAttachmentsById(SpShipFreightAttachments rq) {
        SpShipFreightAttachments freightAttachmentsList = spShipFreightAttachmentsService.queryFreightAttachmentsById(rq);
        if (null != freightAttachmentsList){
            this.updateFreightById(freightAttachmentsList);
        }
        return spShipFreightAttachmentsService.updateFreightAttachmentsById(rq);
    }

    @Override
    public SmShipFreightCost queryFreightById(Long costId) {
        return baseMapper.selectById(costId);
    }


    @Override
    public JsonResult queryRecordById(Long costId,String processInstanceId,String key) {
        SmShipFreightCost freightCost = baseMapper.selectById(costId);
        if (null != freightCost && "2".equals(freightCost.getDataSource())){
            return spShipFreightAttachmentsService.queryFreightAttachmentsInfo(freightCost);
        }else {
           return spFobJsfhccbItemsService.getBgCostInfo(costId,processInstanceId,key);
        }
    }

    @Override
    public boolean updateFreightAttachmentsUrl(CreateFreightAttachmentsRq rq) {

        return spShipFreightAttachmentsService.updateFreightAttachmentsUrl(rq);
    }
}




